package com.example.tms.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.tms.common.annotation.LogAction;
import com.example.tms.common.enums.Result;
import com.example.tms.dto.EmployeeDetailDTO;
import com.example.tms.entity.Employee;
import com.example.tms.service.EmployeeService;

@RestController
@RequestMapping("/employees")
public class EmployeeController {

    private static final org.apache.logging.log4j.Logger log =
            org.apache.logging.log4j.LogManager.getLogger(EmployeeController.class);
    @Autowired
    private EmployeeService employeeService;

    // GET 请求：获取所有员工
    @LogAction("查询员工列表")
    @GetMapping ("")// 支持带分页参数
    @PreAuthorize("hasAnyRole('ADMIN','HR','EXECUTIVE')")
    public Result getEmployees(
            @RequestParam(required = false) Integer pageNum,
            @RequestParam(required = false) Integer pageSize) {

        try {
            if (pageNum == null || pageSize == null) {
                List<Employee> list = employeeService.selectAll();
                return Result.success(list);
            }
            IPage<Employee> page = employeeService.selectPage(pageNum, pageSize);
            return Result.success(page);
        } catch (Exception e) {
            return Result.error("查询失败");
        }
    }
    
    // GET 请求：获取所有员工完整信息
    @LogAction("查询所有员工完整信息")
    @PreAuthorize("hasAnyRole('ADMIN','HR','EXECUTIVE')")
    @GetMapping("/details")
    public Result getAllEmployeeDetails() {
        try {
            List<EmployeeDetailDTO> details = employeeService.getAllEmployeeDetails();
            return Result.success(details);
        } catch (Exception e) {
            return Result.error("查询所有员工完整信息失败");
        }
    }

    // GET: 根据 ID 获取员工
    @LogAction("根据id查询员工")
    @GetMapping("/{id}")
    @PreAuthorize("isAuthenticated()")
    public Result selectById(@PathVariable Integer id) {
        try {
            Employee employee = employeeService.selectById(id);
            if (employee == null) {
                return Result.error("员工不存在");
            }
            return Result.success(employee);
        } catch (Exception e) {
            return Result.error("查询失败");
        }
    }
    
    // GET: 获取员工完整信息(包含部门信息)
    @LogAction("查询员工完整信息")
    @GetMapping("/details/{id}")
    @PreAuthorize("isAuthenticated()")
    public Result getEmployeeDetail(@PathVariable Integer id) {
        try {
            EmployeeDetailDTO employeeDetail = employeeService.getEmployeeDetail(id);
            if (employeeDetail == null) {
                return Result.error("员工不存在");
            }
            return Result.success(employeeDetail);
        } catch (Exception e) {
            return Result.error("查询员工完整信息失败");
        }
    }

    // POST: 添加员工
    @LogAction("添加员工")
    @PostMapping("")
    @PreAuthorize("hasAnyRole('ADMIN','HR')")
    public Result add(@RequestBody Employee employee) {

        try {
            int result = employeeService.insert(employee);
            if (result > 0) {
                return Result.success();
            }
            return Result.error("添加失败");
        } catch (Exception e) {
            return Result.error("系统错误");
        }
    }

    // PUT: 更新员工信息
    @LogAction("更新员工")
    @PutMapping("/{id}")
    @PreAuthorize("hasAnyRole('ADMIN','HR')")
    public Result update(@PathVariable Integer id, @RequestBody Employee employee) {

        try {
            employee.setId(id);
            int result = employeeService.update(employee);
            if (result > 0) {
                return Result.success();
            }
            return Result.error("更新失败");
        } catch (Exception e) {
            return Result.error("系统错误");
        }
    }

    // DELETE: 删除员工
    @LogAction(value = "删除员工", level = "WARN")
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAnyRole('ADMIN','HR')")
    public Result delete(@PathVariable Integer id) {

        try {
            int result = employeeService.deleteById(id);
            if (result > 0) {
                return Result.success();
            }
            return Result.error("删除失败");
        } catch (Exception e) {
            return Result.error("系统错误");
        }
    }

    @LogAction("添加员工及部门信息")
    @PostMapping("/with-department")
    @PreAuthorize("hasAnyRole('ADMIN','HR')")
    public Result createWithDepartment(@RequestBody EmployeeDetailDTO dto) {
        try {
            // 基本参数校验
            if (dto.getName() == null || dto.getPassword() == null) {
                return Result.error("姓名和密码不能为空");
            }
            if (dto.getDepId() == null || dto.getPosition() == null) {
                return Result.error("部门和职位不能为空");
            }

            int result = employeeService.createEmployeeWithDepartment(dto);
            return result > 0 ? Result.success() : Result.error("添加失败");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    // PUT: 更新员工及部门信息
    @LogAction("更新员工及部门信息")
    @PutMapping("/with-department/{id}")
        @PreAuthorize("hasAnyRole('ADMIN','HR')")
    public Result updateWithDepartment(@PathVariable Integer id, @RequestBody EmployeeDetailDTO dto) {
        try {
            dto.setId(id); // 确保ID一致
            int result = employeeService.updateEmployeeWithDepartment(dto);
            return result > 0 ? Result.success() : Result.error("更新失败");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
}
